package com.itheima.service.Impl;

import com.itheima.common.utils.POIUtils;
import com.itheima.dto.OrderSettingDTO;
import com.itheima.mapper.OrderSettingMapper;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import com.itheima.vo.OrderSettingVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingMapper orderSettingMapper;

    /**
     * 下载预约设置模板
     *
     * @param response
     */
    public void download(HttpServletResponse response) {
        //设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment;filename=ordersetting_template.xlsx");

        //从类路径读取模板文件并下载到浏览器
        // 尝试使用资源文件作为输入流，确保资源使用后自动关闭，避免资源泄露
        try (InputStream is = getClass().getClassLoader().getResourceAsStream("templates/ordersetting_template.xlsx")) {
            // 初始化长度变量和缓冲区，用于读取和传输数据
            int len = 0;
            byte[] buffer = new byte[1024];

            // 循环读取输入流中的数据，直到到达文件末尾
            while ((len = is.read(buffer)) != -1) {
                // 将读取的数据写入响应的输出流中，实现文件下载或传输
                response.getOutputStream().write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传预约设置文件
     *
     * @param file
     */
    public void upload(MultipartFile file){
        try {
            //从excel文件中读取数据
            List<String[]> list = POIUtils.readExcel(file);

            //将数据保存到数据库中
            for (String[] strings : list) {
                //创建一个OrderSetting对象
                OrderSetting orderSetting = new OrderSetting();

                //设置日期
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
                Date orderDate = simpleDateFormat.parse(strings[0]);

                //设置可预约数量
                Integer number = Integer.parseInt(strings[1]);

                orderSetting.setOrderDate(orderDate);
                orderSetting.setNumber(number);

                JudgeAndUpdate(orderSetting);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据月份查询预约设置
     *
     * @param month
     * @return
     */
    public List<Map<String, Integer>> getOrderSettingByMonth(String month){
        //  将字符串转换成LocalDate对象
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M");
        YearMonth yearMonth = YearMonth.parse(month, formatter);

        // 获取当月的开始日期和结束日期
        LocalDate startDate = yearMonth.atDay(1);
        LocalDate endDate = yearMonth.atEndOfMonth();

        // 查询当月的预约设置数据
        List<OrderSetting> orderSettingList = orderSettingMapper.getOrderSettingByMonth(startDate, endDate);

        //创建一个OrderSettingVO集合，用于存储转换后的数据
        List<OrderSettingVO> orderSettingVOList = new ArrayList<>();

        //遍历查询结果，将OrderSetting对象转换为OrderSettingVO对象，并添加到集合中
        for (OrderSetting orderSetting : orderSettingList) {

            //创建一个OrderSettingVO对象，用于存储转换后的数据
            OrderSettingVO orderSettingVO = new OrderSettingVO();

            //将OrderSetting对象中的数据复制到OrderSettingVO对象中
            BeanUtils.copyProperties(orderSetting, orderSettingVO);
            orderSettingVOList.add(orderSettingVO);
        }

        List<Map<String, Integer>> result = orderSettingVOList.stream().map(item -> {
            Map<String, Integer> map = new HashMap<>();
            Calendar cal = Calendar.getInstance();
            cal.setTime(item.getOrderDate());
            map.put("date", cal.get(Calendar.DAY_OF_MONTH)); // 当月中的第几天
            map.put("number", item.getNumber());
            map.put("reservations", item.getReservations());
            return map;

        }).collect(Collectors.toList());

        return result;
    }

    /**
     * 设置每天可预约人数
     *
     * @param orderSettingDTO
     */
    public void editNumberByOrderDate(OrderSettingDTO orderSettingDTO) {

        //日期
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date orderDate = null;
        try {
            orderDate = simpleDateFormat.parse(orderSettingDTO.getOrderDate());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //可预约人数
        Integer number = orderSettingDTO.getNumber();

        //封装到新的OrderSetting对象
        OrderSetting orderSetting = new OrderSetting();
        orderSetting.setOrderDate(orderDate);
        orderSetting.setNumber(number);

        //设置每天可预约人数
        JudgeAndUpdate(orderSetting);

    }

    /**
     * 判断当前日期是否已存在并设置可预约人数
     *
     * @param newOrderSetting
     */
    private void JudgeAndUpdate(OrderSetting newOrderSetting) {
        //判断当前日期是否已经存在
        OrderSetting orderSetting = orderSettingMapper.getByOrderDate(newOrderSetting);
        if (orderSetting != null) {
            //如果存在，则修改
            orderSetting.setNumber(newOrderSetting.getNumber());
            orderSettingMapper.updateByOrderDate(orderSetting);
        } else {
            //如果不存在，则添加
            orderSettingMapper.insertNumberByOrderDate(newOrderSetting);
        }
    }
}
